<template>
  <div class="TableCustom">
    <table class="table-box-html">
      <tr v-for="(item, itemIndex) in list" :key="item.rows_id" :data-id="item.rows_id">
        <td v-for="(inner, innerIndex) in item.td_arr" :key="inner.cols_id" :data-id="inner.cols_id" style="height: 30px">
          <div v-if="pdf == 1" style="text-align: center" v-html='inner[inner.cols_id + "_text"]'>
          </div>
          <el-input v-else v-model="inner[inner.cols_id + '_text']" type="textarea" autofocus
                    :ref="`textarea_${itemIndex}_${innerIndex}`"
                    @keydown.native="handleKeydown($event, itemIndex, innerIndex)"></el-input>
        </td>
      </tr>
    </table>
  </div>
</template>



<script>
import { timeFormatter } from "UTILS/format";
import { simDeepCopy, getStorage, setStorage } from "UTILS/util";
import { CONSENT_GET_DOCTOR_DZQM } from "_SERVICES/api";

export default {
  name: "TableCustom",
  props: {
    info: {},
    pdf: {},
  },
  data() {
    return {
      list: [],
    };
  },
  created() { },
  watch: {
    info: {
      handler(val) {
        console.log(val);
        let defaultArray = JSON.parse(JSON.stringify(this.list));
        if (val.field_value) {
          defaultArray = JSON.parse(val.field_value);
        }

        if (defaultArray.length == 0) {
          for (let i = 0; i < val.field_rows; i++) {
            let cols_arr = [];
            for (let j = 0; j < val.field_cols; j++) {
              cols_arr.push({
                rows_id: "rows_" + i,
                cols_id: "rows_" + i + "_cols_" + j,
                ["rows_" + i + "_cols_" + j + "_text"]: "",
              });
            }

            defaultArray.push({
              rows_id: "rows_" + i,
              td_arr: cols_arr,
            });
          }
          return (this.list = defaultArray);
        } else {
          let rows = val.field_rows;
          var cols = val.field_cols;

          if (defaultArray.length > rows) {
            defaultArray.length = rows;
          }
          if (defaultArray[0].td_arr.length > cols) {
            defaultArray.forEach((inner) => {
              inner.td_arr.length = cols;
            });
          }

          var expandedArray = [];
          // 遍历行数
          for (let i = 0; i < rows; i++) {
            // 如果原数组中存在该行，则将该行直接添加到扩充后的数组中
            if (defaultArray[i]) {
              let row = defaultArray[i];
              for (let j = 0; j < cols; j++) {
                if (!row.td_arr[j]) {
                  //如果不存在这一行
                  row.td_arr.push({
                    rows_id: "rows_" + i,
                    cols_id: "rows_" + i + "_cols_" + j,
                    ["rows_" + i + "_cols_" + j + "_text"]: "",
                  });
                }
              }
              expandedArray.push(row);
            } else {
              // 如果原数组中不存在该行，则创建一个新的空数组
              var newCol = [];
              // 遍历列数，为新的行添加默认对象
              for (let j = 0; j < cols; j++) {
                // 这里可以根据需求设定默认的对象结构
                newCol.push({
                  rows_id: "rows_" + i,
                  cols_id: "rows_" + i + "_cols_" + j,
                  ["rows_" + i + "_cols_" + j + "_text"]: "",
                });
              }
              // 将新的行添加到扩充后的数组中
              expandedArray.push({
                rows_id: "rows_" + i,
                td_arr: newCol,
              });
            }
          }

          this.list = expandedArray;
        }
      },
      deep: true, // 使用 deep 选项进行深度监视
      immediate: true,
    },
  },
  mounted() {
    let _this = this;
    var TableCustoms = document.getElementsByClassName("TableCustom");

    for (var i = 0; i < TableCustoms.length; i++) {
      // 给每个 input 元素添加 input 事件监听器
      TableCustoms[i].addEventListener("input", function() {
        // 输入框的值发生改变时执行的操作
        _this.info.field_value = JSON.stringify(_this.list);
      });
    }

    // document.addEventListener("input", function() {
    //   // 输入框的值发生改变时执行的操作
    //   _this.info.field_value = JSON.stringify(_this.list);
    // });
  },
  destroyed() { },
  methods: {
    handleKeydown(event, rowIndex, colIndex) {
      const totalRows = this.list.length;
      const totalCols = this.list[0].td_arr.length || 0;
      if (totalRows && totalCols) {
        if (event.key === 'ArrowDown' && rowIndex < totalRows - 1) {
          this.$refs[`textarea_${rowIndex + 1}_${colIndex}`][0].focus();
        } else if (event.key === 'ArrowUp' && rowIndex > 0) {
          this.$refs[`textarea_${rowIndex - 1}_${colIndex}`][0].focus();
        } else if (event.key === 'ArrowRight' && colIndex < totalCols - 1) {
          this.$refs[`textarea_${rowIndex}_${colIndex + 1}`][0].focus();
        } else if (event.key === 'ArrowLeft' && colIndex > 0) {
          this.$refs[`textarea_${rowIndex}_${colIndex - 1}`][0].focus();
        }
      }


    }
  },
};
</script>

<style  lang="less">
.table-box-html {
  width: 100%;
  border-collapse: collapse;

  /* 合并单元格边框 */
  td {
    border: 1px solid #000;
  }
}
</style>

